/**
* <p>Title: UserServiceImpl.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2015</p>
* <p>Company: SiySoft</p>
* @author liguanghui
* @date 2015年5月28日
* @version 1.0
*/
package com.siysoft.tc.base.service.impl;

import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.siysoft.tc.base.bean.bo.AccountBo;
import com.siysoft.tc.base.bean.bo.AssessmentBo;
import com.siysoft.tc.base.bean.bo.AvatarBo;
import com.siysoft.tc.base.bean.bo.InterestBo;
import com.siysoft.tc.base.bean.bo.MessageBo;
import com.siysoft.tc.base.bean.bo.PaginationBo;
import com.siysoft.tc.base.bean.bo.PersonalChatBo;
import com.siysoft.tc.base.bean.bo.ReservationBo;
import com.siysoft.tc.base.bean.bo.ReservationDetailBo;
import com.siysoft.tc.base.bean.bo.ReservationHistoryBo;
import com.siysoft.tc.base.bean.bo.SystemMessageBo;
import com.siysoft.tc.base.bean.bo.UserBo;
import com.siysoft.tc.base.bean.property.ResourceType;
import com.siysoft.tc.base.bean.to.EvaluateTeacher;
import com.siysoft.tc.base.bean.to.Interest;
import com.siysoft.tc.base.bean.to.PersonalChat;
import com.siysoft.tc.base.bean.to.Reservation;
import com.siysoft.tc.base.bean.to.Resource;
import com.siysoft.tc.base.bean.to.RoleUser;
import com.siysoft.tc.base.bean.to.School;
import com.siysoft.tc.base.bean.to.Teacher;
import com.siysoft.tc.base.bean.to.User;
import com.siysoft.tc.base.bean.to.UserInterest;
import com.siysoft.tc.base.bean.to.UserReservation;
import com.siysoft.tc.base.bean.to.VOrderReservation;
import com.siysoft.tc.base.bean.to.VSystemMessage;
import com.siysoft.tc.base.bean.to.VTeacher;
import com.siysoft.tc.base.bean.to.VUserReservation;
import com.siysoft.tc.base.exception.DuplicateUserException;
import com.siysoft.tc.base.exception.EmailAlreadyExistException;
import com.siysoft.tc.base.exception.NoSuchUserException;
import com.siysoft.tc.base.exception.PhoneNumberAlreadyExistException;
import com.siysoft.tc.base.service.IUserService;
import com.siysoft.util.COMMON;
import com.siysoft.util.IMap;
import com.siysoft.util.fileupload.FileUtil;
import com.tc.base.dao.BaseDAO;

/**
 * <p>Title: UserServiceImpl</p>
 * <p>Description: </p>
 * <p>Company: yihaoxue</p>
 * @author    victoryu
 * @date       2015年9月11日
 */
@Service
public class UserServiceImpl implements IUserService {
	
	@Autowired
	BaseDAO baseDao;

	/* （非 Javadoc）
	* <p>Title: getUserById</p>
	* <p>Description: </p>
	* @param user_id
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.UserService#getUserById(int)
	*/
	@Override
	public User getUserById(int user_id) {
		return (User) baseDao.findById(User.class, user_id);
	}
	
	
	/* （非 Javadoc）
	* <p>Title: changehead</p>
	* <p>Description: </p>
	* @param Telephone
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.UserService#changehead(java.lang.String)
	*/
	
	
	public String getResource(int data_id, String type) {
		String hql= "from Resource a where a.dataType='"+type+"' AND a.dataId="+data_id;
		List<Resource> resourcelist =baseDao.findByHQL(hql);
		Resource resource1=new Resource();
		if(resourcelist.size()!=0){
			return resourcelist.get(0).getImgPath();
		}
		return null;
		
	}
	
	

	/* （非 Javadoc）
	* <p>Title: getUserByTelephone</p>
	* <p>Description: </p>  
	* @param Telephone
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.UserService#getUserByTelephone(java.lang.String)
	*/
	@Override
	public User getUserByTelephone(String telephone) throws DuplicateUserException {
		String hql="from User where telephone='"+telephone+"'";
		List<User> users=baseDao.findByHQL(hql);
		if(users.size()>1){
			throw new DuplicateUserException(telephone);
		}
		else if(users.size()==0){
			return null;
		}
		else{
			return users.get(0);
		}
		
	}

	
	
	/* （非 Javadoc）
	* <p>Title: changehead</p>
	* <p>Description: </p>
	* @param Telephone
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.UserService#changehead(java.lang.String)
	*/
	
	@Override
	public void changehead(Resource resource, String local){
		String hql= "from Resource a where a.dataType='"+ResourceType.USER_AVATAR+"' AND a.userId="+resource.getUserId();
		List<Resource> resourcelist =baseDao.findByHQL(hql);
		if(resourcelist.size()!=0){
			try {
				FileUtil.delete(local + resourcelist.get(0).getImgPath());
			} catch (FileNotFoundException e) {
				System.out.println("文件不存在");
			}
		}
		resource.setImgPath(resource.getImgPath().substring(1));
		Resource resource1=resource;
		if(resourcelist.size()!=0){
			resource1=resourcelist.get(0);
			resource1.setUploadTime(resource.getUploadTime());
			resource1.setImgPath(resource.getImgPath());
		}
		
		baseDao.saveOrupdate(resource1);
		
	}

	/* （非 Javadoc）
	* <p>Title: updateUser</p>
	* <p>Description: </p>
	* @param User
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.UserService#updateUser(User user)
	*/
	@Override
	public void updateUser(User user) {
		baseDao.update(user);
		
	}


	/* （非 Javadoc）
	* <p>Title: getUserByEmailOrTelephone</p>
	* <p>Description: </p>
	* @param emailOrPhone
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.IUserService#getUserByEmailOrTelephone(java.lang.String)
	*/
	@Override
	public User getUserByEmailOrTelephone(String emailOrPhone) throws DuplicateUserException, NoSuchUserException {
		String hql="from User where telephone='"+emailOrPhone+"' or email='"+emailOrPhone+"'";
		List<User> users=baseDao.findByHQL(hql);
		if(users.size()>1){
			throw new DuplicateUserException(emailOrPhone);
		}
		else if(users.size()==0){
			throw new NoSuchUserException(emailOrPhone);
		}
		else{
			return  users.get(0);
		}
	}
	



	/* （非 Javadoc）
	* <p>Title: insertUser</p>
	* <p>Description: </p>
	* @param user
	* @see com.siysoft.yihaoxue.app.center.service.IUserService#insertUser(com.siysoft.yihaoxue.base.bean.to.User)
	*/
	@Override
	public int insertUser(User user) {
		return (Integer)baseDao.saveReturnId(user);
	}


	/* （非 Javadoc）
	* <p>Title: count</p>
	* <p>Description: </p>
	* @param userid
	* @return
	* @see com.siysoft.yihaoxue.app.center.service.IUserService#count(java.lang.String)
	*/
	@Override
	public BigDecimal count(String userid) throws Exception {
		
		String hql="SELECT  sum(a.trade_price) as price from db_trade a where a.trade_type=5 and a.user_id="+userid;
		List<Map<String, String>> list=baseDao.findBySQLToMap(hql,null,-1,-1);
		Object  count=0.00;
		if(list.size()!=0){
			Map<String, String> price = list.get(0);
			
			for(Map.Entry<String, String> entry:price.entrySet()){    
				 
				count=entry.getValue() ;   
			}   
			
		}
		if(count==null||count==""){
			count=0.00;
		}
		return new BigDecimal(count.toString());
	}


	/* （非 Javadoc）
	* <p>Title: checkPhoneAndEmailUnique</p>
	* <p>Description: </p>
	* @param phone
	* @param email
	* @return
	* @throws PhoneNumberAlreadyExistException
	* @throws EmailAlreadyExistException
	* @see com.siysoft.yihaoxue.app.center.service.IUserService#checkPhoneAndEmailUnique(java.lang.String, java.lang.String)
	*/
	@Override
	public void checkPhoneAndEmailUnique(String phone, String email)
			throws PhoneNumberAlreadyExistException,
			EmailAlreadyExistException {
		String sql="from User where username='"+phone+"'";
		List<User> userList=new ArrayList();
		if(phone!=null){
			userList=baseDao.findByHQL(sql);
			if(userList.size()>0){
				throw new PhoneNumberAlreadyExistException();
			}
		}
		if(email!=null){
			sql="from User where email='"+email+"'";
			userList=baseDao.findByHQL(sql);
			if(userList.size()>0){
				throw new EmailAlreadyExistException();
			}
		}
		
	}
	
	/**
	* <p>Title: checkPhoneUnique</p>
	* <p>Description: </p>
	* @author victoryu
	* @param phone
	* @return
	* @throws PhoneNumberAlreadyExistException
	**/
	
	@Override
	public boolean HasUser(String phone){
		String sql="from User where telephone='"+phone+"'";
		List<User> userList=new ArrayList();
		if(phone!=null){
			userList=baseDao.findByHQL(sql);
			if(userList.size()>0){
				return true;
			}
			else
			{
				return false;
			}
		}
		return false;
		
	}
	/* （非 Javadoc）
	* <p>Title: InsertTeacher</p>
	* <p>Description: </p>
	* @param teacher
	* @see com.siysoft.yihaoxue.app.center.service.IUserService#InsertTeacher(com.siysoft.yihaoxue.base.bean.to.Teacher)
	*/
	@Override
	public int InsertTeacher(Teacher teacher) {
//		baseDao.save(teacher);
		return (Integer)baseDao.saveReturnId(teacher);
	}
	
	
	
	/* （非 Javadoc）
	 * <p>Title: getActProOrder</p>
	 * <p>Description:实现获取交易记录列表 </p>
	 * @param iMap
	 * @return
	 * @see com.siysoft.yihaoxue.app.course.service.IOrderService#getActProOrder(iMap)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String, String>> getTrading(IMap iMap) throws Exception {
		String hql="SELECT * from db_trade a where a.user_id="+iMap.getString("user_id")+" ORDER BY a.trade_date desc";

		String page=iMap.getString("page");
		
		return baseDao.findBySQLToMap(hql,null,Integer.parseInt(page)*10,10);
	}


	@Override
	public void updateRoleUser(RoleUser roleuser) {
		// TODO Auto-generated method stub
		baseDao.save(roleuser);
	}
	
	@Override
	public boolean checkInviteKey(String key) {
		String sql = "from User where inviteKey='"+key+"'";
		List<?> result = baseDao.findByHQL(sql);
		return result != null && !result.isEmpty();
	}


	@Override
	public User createUser(String name, String telephone, String email,
			String password,String grade) {
		String hql = "from User where user_name='"+name+"' or user_email='"+email+"' or user_telephone='"+telephone+"'" ;
		List<User> users = baseDao.findByHQL(hql);
		if(users.size() == 0){
			User user = new User();
			user.setUser_name(name);
			user.setUser_telephone(telephone);
			user.setUser_email(email);
			user.setUser_password(password);
			user.setUser_up(0);
			user.setUser_down(0);
			user.setUser_grade((grade==null)?"":grade);
			user.setUser_create_time(new Timestamp(System.currentTimeMillis()));
			user.setTeacher_pt_mr_type(0);
			user.setTeacher_level_type(0);//默认不显示，根据0610网页修改条例
			user.setUser_lock(0);
			int user_id = (Integer)baseDao.saveReturnId(user);
			User tmp_user = (User)baseDao.findById(User.class, user_id);
			return tmp_user;
		}
		else{
			return null;
		}
	}
	
	@Override
	public Integer judgeName(String name) {
		// TODO Auto-generated method stub
		String hql = "from User where user_name='"+name+"'";
		List<User> user = baseDao.findByHQL(hql);
		if(user.size() == 0){
			return 1;
		}
		else{
			return -1;
		}
	}


	@Override
	public Integer judgeTelephone(String telephone) {
		// TODO Auto-generated method stub
		String hql = "from User where user_telephone='"+telephone+"'";
		List<User> user = baseDao.findByHQL(hql);
		if(user.size() == 0){
			return 1;
		}
		else{
			return -1;
		}
	}


	@Override
	public Integer judgeEmail(String email) {
		// TODO Auto-generated method stub
		String hql = "from User where user_email='"+email+"'";
		List<User> user = baseDao.findByHQL(hql);
		if(user.size() == 0){
			return 1;
		}
		else{
			return -1;
		}
	}

	@Override
	public Integer completeUser(Integer id, String school,
			String student_id) {
		User user = (User)baseDao.findById(User.class, id);
		user.setUser_school(school);
		user.setUser_student_id(student_id);
		baseDao.update(user);
		return 1;
	}

	@Override
	public Integer setInterest(Integer id, JSONArray interest) {
		// TODO Auto-generated method stub
		for(Integer i = 0; i < interest.size(); i++){
			JSONObject tmp_interest = (JSONObject)interest.get(i);
			UserInterest user_interest = new UserInterest();
			user_interest.setUser_id(id);
			user_interest.setInterest_id(Integer.valueOf(tmp_interest.get("interest_id").toString()));
			baseDao.save(user_interest);
		}
		return 1;
	}
	
	@Override
	public List<InterestBo> getInterest(PaginationBo pb) {
		// TODO Auto-generated method stub
		try {
			String hql = "from Interest";
			List<Interest> li = (List<Interest>) baseDao.findByHQL(hql, null, pb.getPagination_offset(), pb.getPagination_limit());
			pb.setPagination_total(baseDao.findByHQL(hql).size());
			List<InterestBo> lib = new ArrayList<InterestBo>();
			for(Integer i = 0; i < li.size(); i++){
				Interest l = li.get(i);
				int interest_id = l.getInterest_id();
				String interest_name = l.getInterest_name();
				String interest_avatar = COMMON.NulltoAvatar(this.getResource(interest_id,ResourceType.INTEREST));
				InterestBo ib = new InterestBo(interest_id, interest_name, interest_avatar);
				lib.add(ib);
			}
			return lib;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public List<InterestBo> getTeacherCourseList(PaginationBo pb,
			String teacher_name) {
		// TODO Auto-generated method stub
		try {
			
			String hql = "from VTeacher where user_name='" + teacher_name + "'";
			List<VTeacher> vt = baseDao.findByHQL(hql);
			List<InterestBo> lib = new ArrayList<InterestBo>();
			String [] teacher_course = vt.get(0).getTeacher_course().split(",");
			for(Integer i = 0; i < teacher_course.length; i++){
				Integer interest_id = Integer.parseInt(teacher_course[i]);
				Interest interest = (Interest) baseDao.findById(Interest.class, interest_id);
				String interest_name = interest.getInterest_name();
				String interest_avatar = COMMON.NulltoAvatar(this.getResource(interest_id,ResourceType.INTEREST));
				InterestBo ib = new InterestBo(interest_id, interest_name, interest_avatar);
				lib.add(ib);
			}
			
			return lib;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public List<School> getSchool() {
		// TODO Auto-generated method stub
		try {
			String hql = "from School";
			List<School> school = new ArrayList<School>();
			school = baseDao.findByHQL(hql);
			return school;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public User login(String name_email_studentid) {
		// TODO Auto-generated method stub
		String hql = "from User where user_name='"+name_email_studentid+"' or user_email='"+name_email_studentid+"' or user_student_id='"+name_email_studentid+"'";
		List<User> user = baseDao.findByHQL(hql);
		if(user.size() == 0){
			return null;
		}
		else{
			return user.get(0);
		}
	}


	@Override
	public UserBo getUserInfo(Integer id, PaginationBo reservation_pb, PaginationBo assessment_pb) {
		// TODO Auto-generated method stub
		try {
			String hql1 = "from User where user_id="+id;
			List<User> user = baseDao.findByHQL(hql1);
			
			String hql2 = "from VUserReservation where user_id="+id + " and user_reservation_status=5";
			List<VUserReservation> user_reservation;
			
			user_reservation = (List<VUserReservation>) baseDao.findByHQL(hql2, null, reservation_pb.getPagination_offset(), reservation_pb.getPagination_limit());
			reservation_pb.setPagination_total(baseDao.findByHQL(hql2).size());
			List<ReservationHistoryBo> reservation_history = new ArrayList<ReservationHistoryBo>();
			for(Integer i = 0; i < user_reservation.size(); i++){
				VUserReservation vur = user_reservation.get(i);
				int reservation_history_id = vur.getReservation_id();
				String reservation_history_number = vur.getReservation_number();
				String reservation_history_course = vur.getReservation_course();
				Long reservation_history_time = vur.getReservation_time().getTime();
				Integer reservation_history_goal = vur.getReservation_goal();
				String reservation_history_teacher_name = vur.getReservation_lecture();
				ReservationHistoryBo rhb = new ReservationHistoryBo(reservation_history_id,
						reservation_history_number, reservation_history_course, reservation_history_time,
						reservation_history_goal, reservation_history_teacher_name);
				reservation_history.add(rhb);
			}
			
			String hql3 = "from EvaluateTeacher where evaluate_student_id="+id;
			List<EvaluateTeacher> let = (List<EvaluateTeacher>) baseDao.findByHQL(hql3, null, assessment_pb.getPagination_offset(), assessment_pb.getPagination_limit());
			assessment_pb.setPagination_total(baseDao.findByHQL(hql3).size());
			List<AssessmentBo> assessment = new ArrayList<AssessmentBo>();
			for(Integer i = 0; i < let.size(); i++){
				EvaluateTeacher et = let.get(i);
				Integer assessment_id = et.getEvaluate_id();
				Integer assessment_user_id = et.getEvaluate_teacher_id();
				User tmp_u = (User) baseDao.findById(User.class, assessment_user_id);
				String assessment_user_name = tmp_u.getUser_name();
				Timestamp assessment_time = et.getEvaluate_time();
				String assessment_content = et.getEvaluate_content();
				String assessment_user_avatar = COMMON.NulltoAvatar(this.getResource(assessment_user_id,ResourceType.USER_AVATAR));
				AssessmentBo ab = new AssessmentBo(assessment_id, assessment_user_name, 
						assessment_time, assessment_content, assessment_user_avatar);
				assessment.add(ab);
			}
			
			User us = user.get(0);
			String user_avatar = COMMON.NulltoAvatar(this.getResource(us.getUser_id(),ResourceType.USER_AVATAR));
			UserBo user_return = new UserBo(us.getUser_id(), us.getUser_grade(),
					us.getUser_email(), us.getUser_name(), us.getUser_student_id(),
					us.getUser_telephone(), reservation_history, reservation_pb, 
					assessment, assessment_pb, user_avatar,
					us.getUser_up(), us.getUser_down(), us.getUser_school(), us.getUser_type());
			return user_return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public List<ReservationBo> getReservation(Integer id) {
		// TODO Auto-generated method stub
		//String hql = "from VUserReservation where user_id="+id;
		String hql = "from VUserReservation where user_id="+id+" and user_reservation_status<5 Order by reservation_time desc";
		List<VUserReservation> reservation = baseDao.findByHQL(hql);
		List<ReservationBo> reservation_bo = new ArrayList<ReservationBo>();
		for(Integer i = 0; i < reservation.size(); i++){
			VUserReservation r = reservation.get(i);
			int reservation_id = r.getReservation_id();
			String reservation_number = r.getReservation_number();
			Integer reservation_status = r.getReservation_status();
			Integer reservation_ispublic = r.getReservation_ispublic();
			String reservation_course = r.getReservation_course();
			Timestamp reservation_time = r.getReservation_time();
			String reservation_address = r.getReservation_address();
			Integer user_reservation_status = r.getUser_reservation_status();
			ReservationBo rb = new ReservationBo(reservation_id, reservation_number, 
					reservation_status, reservation_ispublic, reservation_course, 
					reservation_time, reservation_address, user_reservation_status);
			reservation_bo.add(rb);
		}
		return reservation_bo;
	}


	@Override
	public List<AccountBo> getAccount(Integer id, PaginationBo pb) {
		// TODO Auto-generated method stub
		try {
			String hql = "from VOrderReservation where user_id="+id;
			List<VOrderReservation> vor = (List<VOrderReservation>) baseDao.findByHQL(hql, null, pb.getPagination_offset(), pb.getPagination_limit());
			pb.setPagination_total(baseDao.findByHQL(hql).size());
			List<AccountBo> account_bo = new ArrayList<AccountBo>();
			for(Integer i = 0; i < vor.size(); i++){
				VOrderReservation a = vor.get(i);
				int account_id = a.getOrder_id();
				String account_course = a.getReservation_course();
				String account_reservation_number = a.getReservation_number();
				Long account_time = a.getOrder_cdate().getTime();
				Integer account_money = a.getOrder_price();
				Integer account_status = a.getOrder_status();
				Integer account_type = a.getOrder_type();
				AccountBo ab = new AccountBo(account_id, account_course, 
						account_reservation_number, account_time,
						account_money, account_status, account_type);
				account_bo.add(ab);	
			}
			return account_bo;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public List<SystemMessageBo> getSystemMessage(Integer id, PaginationBo pb) {
		// TODO Auto-generated method stub
		try {
			String hql = "from VSystemMessage where user_id="+id;
			List<VSystemMessage> system_message = (List<VSystemMessage>) baseDao.findByHQL(hql, null, pb.getPagination_offset(), pb.getPagination_limit());
			pb.setPagination_total(baseDao.findByHQL(hql).size());
			List<SystemMessageBo> system_message_bo = new ArrayList<SystemMessageBo>();
			for(Integer i = 0; i < system_message.size(); i++){
				VSystemMessage vsm = system_message.get(i);
				int system_message_id = vsm.getMessage_id();
				int system_message_user_id = vsm.getUser_id();
				String system_message_content = vsm.getContent();
				SystemMessageBo smb = new SystemMessageBo(system_message_id, 
						system_message_user_id, system_message_content);
				system_message_bo.add(smb);
			}
			return system_message_bo;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public List<MessageBo> getMessage(Integer id, PaginationBo pb) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public List<MessageBo> getMessageDetail(Integer id, PaginationBo pb) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public Integer reply(Integer id, Integer reciver_id, String message) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public ReservationDetailBo getReservationDetail(Integer user_id, Integer reservation_id, PaginationBo pb) {
		// TODO Auto-generated method stub
		try{
			String hql = "from Reservation where reservation_id="+reservation_id;
			List<Reservation> reservation = baseDao.findByHQL(hql);
			Reservation r = reservation.get(0);
			List<AvatarBo> lab = new ArrayList<AvatarBo>();
			String hql2 = "from UserReservation where reservation_id="+reservation_id;
			List<UserReservation> lur = (List<UserReservation>)baseDao.findByHQL(hql2, null, pb.getPagination_offset(), pb.getPagination_limit());
			for(Integer i = 0; i < lur.size(); i ++){
				UserReservation ur = lur.get(i);
				int avatar_user_id = ur.getUser_id();
				String avatar_url = COMMON.NulltoAvatar(this.getResource(avatar_user_id,ResourceType.USER_AVATAR));
				String avatar_name = ((User)baseDao.findById(User.class, avatar_user_id)).getUser_name();
				AvatarBo ab = new AvatarBo(avatar_user_id, avatar_url,avatar_name);
				lab.add(ab);
			}
			int lecture_id = -1;
			String reservation_detail_teacher_avatar = "";
			String reservation_detail_lecture_name = "";
			if(r.getReservation_lecture_id() != -1){
				lecture_id = r.getReservation_lecture_id();
				reservation_detail_teacher_avatar = COMMON.NulltoAvatar(this.getResource(lecture_id,ResourceType.USER_AVATAR));
				reservation_detail_lecture_name = ((User)baseDao.findById(User.class, lecture_id)).getUser_name();
			}
			
			ReservationDetailBo rdb = new ReservationDetailBo(r.getReservation_id(), r.getReservation_number(),
					r.getReservation_course(), r.getReservation_goal(), r.getReservation_school(),
					r.getReservation_time(), r.getReservation_address(), reservation_detail_lecture_name,
					r.getReservation_period(), r.getReservation_wage(), r.getReservation_bonus(), r.getReservation_ispublic(),
					r.getReservation_max_size(), r.getReservation_current_size(), r.getReservation_status(),
					lab, pb, r.getReservation_create_id(), lecture_id, reservation_detail_teacher_avatar,reservation_detail_lecture_name );
			return rdb;
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}


	@Override
	public Integer getUserReservationStatus(Integer user_id, Integer reservation_id) {
		// TODO Auto-generated method stub
		String hql = "from UserReservation where user_id="+user_id+" and reservation_id="+reservation_id;
		List<UserReservation> ur = baseDao.findByHQL(hql);
		Integer user_reservation_status = -1;
		if(ur.size() > 0){
			user_reservation_status = ur.get(0).getUser_reservation_status();
		}
		return user_reservation_status;
	}
	
	public String getResourceUrl(String resType, int targetId) {
		String sql="from Resource where dataType='"+resType+"' and userId="+targetId;
		List<Resource> resource=baseDao.findByHQL(sql);
		if(resource.size()==0){
			return null;
		}
			return COMMON.home_url + resource.get(0).getImgPath();
	}


	@Override
	public List<PersonalChatBo> getPersonalChatDetail(Integer user_id1,
			Integer user_id2, PaginationBo pb) {
		// TODO Auto-generated method stub
		try{
			String hql = "from PersonalChat where (personal_chat_sender_id="+user_id1
					+" and personal_chat_receiver_id="+user_id2+")"
					+ " or (personal_chat_sender_id="+user_id2
					+ " and personal_chat_receiver_id="+user_id1+") order by personal_chat_time";
			List<PersonalChat> lpc = (List<PersonalChat>)baseDao.findByHQL(hql, null, pb.getPagination_offset(), pb.getPagination_limit());
			pb.setPagination_total(baseDao.findByHQL(hql).size());
			List<PersonalChatBo> lpcb = new ArrayList<PersonalChatBo>();
			for(Integer i = 0; i < lpc.size(); i++){
				PersonalChat pc = lpc.get(i);
				int personal_chat_sender_id = pc.getPersonal_chat_sender_id();
				int personal_chat_receive_id = pc.getPersonal_chat_receiver_id();
				String personal_chat_sender_avatar = COMMON.NulltoAvatar(this.getResource(personal_chat_sender_id,ResourceType.USER_AVATAR));;
				String personal_chat_content = pc.getPersonal_chat_content();
				User tmp_u = (User)baseDao.findById(User.class, personal_chat_sender_id);
				String personal_chat_sender_user_name = tmp_u.getUser_name();
				PersonalChatBo pcb = new PersonalChatBo(personal_chat_sender_id,
						personal_chat_receive_id, personal_chat_sender_user_name, personal_chat_sender_avatar,
						personal_chat_content);
				lpcb.add(pcb);
			}
			return lpcb;
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public String PersonalChatSend(Integer sender_id, Integer receiver_id,
			String content) {
		// TODO Auto-generated method stub
		PersonalChat pc = new PersonalChat();
		pc.setPersonal_chat_sender_id(sender_id);
		pc.setPersonal_chat_receiver_id(receiver_id);
		pc.setPersonal_chat_content(content);
		pc.setPersonal_chat_time(new Timestamp(System.currentTimeMillis()));
		baseDao.save(pc);
		return "success for send";
	}


	@Override
	public List<PersonalChatBo> PersonalChatList(Integer id, PaginationBo pb) {
		// TODO Auto-generated method stub
		try{
			String hql = "select personal_chat_id,personal_chat_sender_id," +
					"personal_chat_receiver_id,max(personal_chat_time) as " +
					"personal_chat_time,personal_chat_content from " +
					"(select * from db_personal_chat  " +
					"where personal_chat_receiver_id =" + id + ") b " +
					"group by personal_chat_sender_id";
			List<Map<String,Object>> lt = (List<Map<String,Object>>)baseDao.findBySQLToMap(hql, null, pb.getPagination_offset(), pb.getPagination_limit());
			List<PersonalChatBo> lpcb = new ArrayList<PersonalChatBo>();
			for(int i = 0;i < lt.size(); i++)
			{
				int personal_chat_sender_id = (Integer)lt.get(i).get("personal_chat_sender_id");
				int personal_chat_receive_id = (Integer)lt.get(i).get("personal_chat_receiver_id");
				User us = (User)baseDao.findById(User.class, personal_chat_sender_id);
				String personal_chat_sender_user_name = us.getUser_name();
				String personal_chat_sender_avatar = COMMON.NulltoAvatar(this.getResource(personal_chat_sender_id,ResourceType.USER_AVATAR));;
				String personal_chat_content = (String)lt.get(i).get("personal_chat_content");
				PersonalChatBo pcb = new PersonalChatBo(personal_chat_sender_id,
						personal_chat_receive_id, personal_chat_sender_user_name,
						personal_chat_sender_avatar, personal_chat_content);
				lpcb.add(pcb);
			}
			return lpcb;
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}


	@Override
	public Integer judgeLecture(String name) {
		// TODO Auto-generated method stub
		String hql = "from User where user_name='"+name+"' and user_type=1";
		List<User> user = baseDao.findByHQL(hql);
		if(user.size() == 0){
			return -1;
		}
		else{
			return 1;
		}
	}


	
	
}
